package Day16.ZuoYe;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

/*products.xml基本信息解释如下：
 unt是库存product为商品信息节点，discount表示是否折扣，如果是折扣商品，打七折；
 factoryaddr是工厂地址；
 itemno为商品编号，name为商品名称，price为商品单价，unit是计价单位，stockco量。
 1：读取products.xml中的商品信息，输出。
 2：查找商品信息：根据输入的商品号，输出对应的商品信息。
 3：修改products.xml，输入商品编号（itemno）和数量，修改对应商品的数量（stockcount）；没有找到商品号，给出提示。
 4：以products.xml作为基础，实现客户购买的方法，输入商品号和购买数量，计算应付金额，如果是折扣商品，打七折；
 如果购买数量超过库存量，给出提示；商品不存在，给出提示；购买成功，扣除相应的数量。最后输出应付款的金额。
 5:增加新商品的功能，要求商品号和商品名称都不能重复（即不能和已经存在的重复）
 */
public class ProductsXML {
    private static final String FILE_PATH = "C:\\Users\\admin\\IdeaProjects\\java78\\javabasic\\src\\TeXing\\src\\Day16\\ZuoYe\\products.xml";

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.println("请选择您需要的操作：\n1、显示所有商品信息；2、查找指定商品；" +
                    "3、修改商品库存量；4、购买结算；5、添加新商品；0、退出");
            int choose = input.nextInt();
            if (choose == 1) {
                System.out.println("******显示所有商品信息******");
                readAll();
            } else if (choose == 2) {
                System.out.println("******查找指定商品******");
                System.out.println("请输入需要查询的商品编号：");
                String no = input.next();
                find(no);
            } else if (choose == 3) {
                System.out.println("******修改商品库存量******");
                System.out.println("请输入需要修改的商品编号：");
                String no = input.next();
                System.out.println("请输入需要修改的商品库存数量：");
                int count = input.nextInt();
                amend(no, count);
            } else if (choose == 4) {
                System.out.println("******购买结算******");
                System.out.println("请输入需要购买的商品编号：");
                String no = input.next();
                System.out.println("请输入需要购买的商品数量：");
                int count = input.nextInt();
                buy(no, count);
            } else if (choose == 5) {
                System.out.println("******添加新商品******");
                System.out.println("请输入新添加的商品编号：");
                String no = input.next();
                System.out.println("请输入新添加的商品名称：");
                String name = input.next();
                System.out.println("请输入新添加的商品价格：");
                double price = input.nextDouble();
                System.out.println("请输入新添加的商品计价单位：");
                String unit = input.next();
                System.out.println("请输入新添加的商品是否为折扣商品：");
                String discount = input.next();
                System.out.println("请输入新添加的商品生产地：");
                String adresss = input.next();
                System.out.println("请输入新添加的商品库存数量：");
                int count = input.nextInt();
                add(no, name, price, unit, discount, count, adresss);
            } else if (choose == 0) {
                System.out.println("******退出******");
                return;
            }
        }
    }

    /*
     * 1：读取products.xml中的商品信息，输出。
     * */
    public static void readAll() {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(FILE_PATH);
            List<Node> list = doc.selectNodes("/shop/product");
            System.out.println("商品信息如下：");
            System.out.println("编号\t\t名称\t\t单价\t\t计价单位\t\t库存量\t\t是否折扣\t\t产地");
            for (Node o : list) {
                Element element = (Element) o;
                String item = element.elementTextTrim("itemno");
                String name = element.elementTextTrim("name");
                double price = Double.parseDouble(element.elementTextTrim("price"));
                int stockcount = Integer.parseInt(element.elementTextTrim("stockcount"));
                String unit = element.elementTextTrim("unit");
                Boolean discount = Boolean.valueOf(element.attributeValue("discount"));
                String factoryaddr = element.attributeValue("factoryaddr");
                System.out.println(item + "\t\t" + name + "\t\t" + price + "\t\t" + unit + "\t\t" + stockcount + "\t\t" + (discount ? "有折扣" : "无折扣") + "\t\t" + factoryaddr);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /*
    2：查找商品信息：根据输入的商品号，输出对应的商品信息。
     */
    public static void find(String no) {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(FILE_PATH);
            List<Node> list = doc.selectNodes("//product[itemno='" + no + "']");
            if (list.size() == 0) {
                System.out.printf("编号%s的商品不存在。", no);
                return;
            }
            Element element = (Element) list.get(0);
            System.out.println("编号" + no + "的商品信息如下：");
            System.out.println("编号\t\t名称\t\t单价\t\t计价单位\t\t库存量\t\t是否折扣\t\t产地");
            String item = element.elementTextTrim("itemno");
            String name = element.elementTextTrim("name");
            String price = element.elementTextTrim("price");
            String stockcount = element.elementTextTrim("stockcount");
            String unit = element.elementTextTrim("unit");
            String discount = element.attributeValue("discount");
            String factoryaddr = element.attributeValue("factoryaddr");
            System.out.println(item + "\t\t" + name + "\t\t" + price + "\t\t" + unit
                    + "\t\t" + stockcount + "\t\t" + (Boolean.valueOf(discount) ? "有折扣" : "无折扣") +
                    "\t\t" + factoryaddr);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /*
3：修改products.xml，输入商品编号（itemno）和数量，修改对应商品的数量（stockcount）；没有找到商品号，给出提示。*/
    public static void amend(String no, int count) {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(FILE_PATH);
            List<Node> list = doc.selectNodes("//product[itemno='" + no + "']");
            if (list.size() == 0) {
                System.out.printf("编号%s的商品不存在。", no);
                return;
            }
            Element element = (Element) list.get(0);
            element.selectSingleNode("stockcount").setText(String.valueOf(count));
            XMLWriter xmlWriter = null;
            try {
                OutputFormat prettyPrint = OutputFormat.createPrettyPrint();
                xmlWriter = new XMLWriter(new FileWriter(FILE_PATH), prettyPrint);
                xmlWriter.write(doc);
                xmlWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                System.out.println("更新成功。。。。。。");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /*4：以products.xml作为基础，实现客户购买的方法，输入商品号和购买数量，计算应付金额，如果是折扣商品，打七折；
    如果购买数量超过库存量，给出提示；商品不存在，给出提示；购买成功，扣除相应的数量。最后输出应付款的金额。*/
    public static void buy(String no, int count) {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(FILE_PATH);
            List<Node> list = doc.selectNodes("//product[itemno='" + no + "']");
            if (list.size() == 0) {
                System.out.printf("编号%s的商品不存在！", no);
                return;
            }
            Node node = list.get(0);
            Element element = (Element) node;
            int stockcount = Integer.parseInt(element.elementTextTrim("stockcount"));
            if (stockcount < count) {
                String unit = element.elementTextTrim("unit");
                System.out.printf("您需要购买的商品数量超过仓库存量，无法成交。\n商品剩余%d%s", stockcount, unit);
                return;
            }
            Boolean discount = Boolean.valueOf(element.attributeValue("discount"));
            double price = Double.parseDouble(element.elementTextTrim("price"));
            double money = 0;
            double originalPrice = price * count;
            if (discount) {
                money = originalPrice * 0.7;
                System.out.printf("编号%s的商品属于折扣商品，商品价格打7折。" +
                        "\n本次应支付人民币%f元。\n折后实际支付人民币%f元", no, originalPrice, money);
            } else {
                money = originalPrice;
                System.out.printf("编号%s的商品属于非折扣商品。" +
                        "\n本次应支付人民币%f元。\n实际支付人民币%f元", no, originalPrice, money);
            }
            element.selectSingleNode("stockcount").setText(String.valueOf((stockcount - count)));
            XMLWriter xmlWriter = null;
            try {
                OutputFormat prettyPrint = OutputFormat.createPrettyPrint();
                xmlWriter = new XMLWriter(new FileWriter(FILE_PATH), prettyPrint);
                xmlWriter.write(doc);
                xmlWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    xmlWriter.close();
                    System.out.println("恭喜购买成功，期待下次合作。。。。。。");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /*5:增加新商品的功能，要求商品号和商品名称都不能重复（即不能和已经存在的重复）*/
    public static void add(String no, String name, double price, String unit, String discount,
                           int stockcount, String address) {
        SAXReader reader = new SAXReader();
        Document doc = null;
        try {
            doc = reader.read(FILE_PATH);
            Element root = doc.getRootElement();
            List<Node> list = doc.selectNodes("//product");
            for (Node o : list) {
                Element element = (Element) o;
                String itemno = element.elementTextTrim("itemno");
                String name1 = element.elementTextTrim("name");
                if (itemno.equals(no)) {
                    System.out.printf("您输入的商品编号%s已存在，请核实后再输入！", no);
                    return;
                }
                if (name1.equals(name)) {
                    System.out.printf("您输入的商品名称%s已存在name，请核实后再输入！", name);
                    return;
                }
            }
            Element element1 = root.addElement("product");
            element1.addAttribute("discount", discount);
            element1.addAttribute("factoryaddr", address);
            element1.addElement("itemno").setText(no);
            element1.addElement("name").setText(name);
            element1.addElement("price").setText(String.valueOf(price));
            element1.addElement("stockcount").setText(String.valueOf(stockcount));
            element1.addElement("unit").setText(unit);
            XMLWriter xmlWriter = null;
            try {
                OutputFormat prettyPrint = OutputFormat.createPrettyPrint();
                xmlWriter = new XMLWriter(new FileWriter(FILE_PATH), prettyPrint);
                xmlWriter.write(doc);
                xmlWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    xmlWriter.close();
                    System.out.printf("编号%s的商品添加入库成功。。。。。。", no);
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        } catch (
                DocumentException e) {
            e.printStackTrace();
        }
    }
}
